// utils/auth.ts

export interface UserInfo {
  id: string | number;
  username: string;
  nickname: string;
  avatar: string;
  userType: 'normal' | 'sales';
  phone: string;
  openid?: string;
}

// 状态变化监听器
type AuthStateListener = () => void;
const authStateListeners: AuthStateListener[] = [];

/**
 * 添加认证状态变化监听器
 */
export const addAuthStateListener = (listener: AuthStateListener): void => {
  authStateListeners.push(listener);
};

/**
 * 移除认证状态变化监听器
 */
export const removeAuthStateListener = (listener: AuthStateListener): void => {
  const index = authStateListeners.indexOf(listener);
  if (index > -1) {
    authStateListeners.splice(index, 1);
  }
};

/**
 * 通知所有监听器状态已变化
 */
const notifyAuthStateChange = (): void => {
  authStateListeners.forEach(listener => listener());
};

/**
 * 检查用户是否已登录
 * 基于 access_token 的存在来判断
 */
export const isLoggedIn = (): boolean => {
  const token = uni.getStorageSync('access_token');
  return !!token;
};

/**
 * 获取用户信息
 */
export const getUserInfo = (): UserInfo | null => {
  if (!isLoggedIn()) {
    return null;
  }
  
  const userInfo = uni.getStorageSync('userInfo');
  return userInfo || null;
};



/**
 * 设置用户登录信息
 */
export const setAuthInfo = (token: string, userInfo: UserInfo, refreshToken?: string): void => {
  uni.setStorageSync('access_token', token);
  uni.setStorageSync('userInfo', userInfo);
  if (refreshToken) {
    uni.setStorageSync('refresh_token', refreshToken);
  }
  
  // 通知状态变化
  notifyAuthStateChange();
};

/**
 * 清除登录信息
 */
export const clearAuth = (): void => {
  uni.removeStorageSync('access_token');
  uni.removeStorageSync('refresh_token');
  uni.removeStorageSync('userInfo');
  
  // 通知状态变化
  notifyAuthStateChange();
};

/**
 * 跳转到登录页面
 */
export const goToLogin = (): void => {
  uni.navigateTo({
    url: '/pages/user/login'
  });
};

/**
 * 检查登录状态，未登录则跳转到登录页
 */
export const requireLogin = (): boolean => {
  if (!isLoggedIn()) {
    goToLogin();
    return false;
  }
  return true;
};